package main

import "fmt"

func main() {

	//定义map
	creat()

	//遍历map
	traversing()

	//删除map元素
	deleteMap()

	//map赋值
	set()

	//map取值
	get()
}

func get() {
	fmt.Println("func get():")
	m1 := map[string]string{
		"name":   "weiwei",
		"sex":    "1",
		"age":    "34",
		"salary": "500000",
	}
	fmt.Println("m1:", m1)

	name, ok := m1["name"]
	fmt.Println("name:", name, "ok:", ok)

	nameWrong, ok := m1["mame1"]
	fmt.Println("nameWrong:", nameWrong, "ok:", ok)
	fmt.Println("====================================================")
}

func set() {
	fmt.Println("func set():")

	m1 := map[string]string{
		"name":   "weiwei",
		"sex":    "1",
		"age":    "34",
		"salary": "500000",
	}
	fmt.Println("m1:", m1)
	m1["age"] = "35"
	fmt.Println("m1:", m1)
	fmt.Println("====================================================")
}

func deleteMap() {
	fmt.Println("func deleteMap():")
	m1 := map[string]string{
		"name":   "weiwei",
		"sex":    "1",
		"age":    "34",
		"salary": "500000",
	}
	fmt.Println("m1:", m1)

	delete(m1, "salary")
	fmt.Println("m1:", m1)
	fmt.Println("====================================================")
}

func traversing() {
	fmt.Println("func traversing():")

	//map的遍历不保证顺序不一致
	m1 := map[string]string{
		"name":   "weiwei",
		"sex":    "1",
		"age":    "34",
		"salary": "500000",
	}
	fmt.Println("m1:", m1)

	for k, v := range m1 {
		fmt.Println("k=", k, "v=", v)
	}
	fmt.Println("====================================================")
}

func creat() {
	/**
	1.map使用hash表，必须可以比较相等。
	2.除了slice map function的内建类型都可以作为key。
	3.Struct类型只要不包含slice map function也可以作为key。
	*/
	fmt.Println("func creat():")
	m1 := map[string]string{
		"name":   "weiwei",
		"sex":    "1",
		"age":    "34",
		"salary": "500000",
	}
	fmt.Println("m1:", m1)

	var m2 map[string]string //nil
	if m2 == nil {
		fmt.Println("m2:", m2, "m2 is nil")
	} else {
		fmt.Println("m2:", m2, "m2 is not nil")
	}

	m3 := make(map[string]int) //empty
	if m3 == nil {
		fmt.Println("m3:", m3, "m3 is nil")
	} else {
		fmt.Println("m3:", m3, "m3 is not nil")
	}
	fmt.Println("====================================================")
}
